﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp9
{

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            listView1.View = View.Details;
            listView1.Columns.Add("标题", 250);
            listView1.Columns.Add("网址", 250);
            listView1.Columns.Add("电话", 100);
            label2.Text = "";
        }
        private async  void button1_Click(object sender, EventArgs e)
        {
            listView1.Items.Clear();
            string input = textBox1.Text;
            if (!string.IsNullOrEmpty(input))
            {
                label2.Text = "爬取中";
                var searchResults = await SearchBing(input);
                foreach (var result in searchResults)
                {
                    Console.WriteLine($"Title: {result.Title}");
                    Console.WriteLine($"URL: {result.Url}");
                    var content = await DownloadHtmlContent(result.Url);
                    ExtractChinesePhoneNumbersFromHtml(result, content);
                }
                label2.Text = "爬取完毕";
            }
            else
            {
                label2.Text = "该关键词无信息";
            }
        }
        async Task<List<SearchResult>> SearchBing(string searchQuery)
        {
            using (HttpClient client = new HttpClient())
            {
                string bingSearchUrl = $"https://www.bing.com/search?q={searchQuery}&pageNumber=5&gs_lcrp=EgZjaHJvbWUyBggAEEUYOTIECAEQADIECAIQADIECAMQADIECAQQADIECAUQADIECAYQADIECAcQADIECAgQANIBCDEzNTdqMGo0qAIAsAIA&FORM=ANAB01&mkt=zh-CN";

                HttpResponseMessage response = await client.GetAsync(bingSearchUrl);

                if (response.IsSuccessStatusCode)
                {
                    string htmlContent = await response.Content.ReadAsStringAsync();
                    HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
                    htmlDoc.LoadHtml(htmlContent);

                    var resultNodes = htmlDoc.DocumentNode.SelectNodes("//h2/a[@href]");

                    if (resultNodes != null)
                    {
                        var searchResults = new List<SearchResult>();
                        foreach (var resultNode in resultNodes)
                        {
                            string title = resultNode.InnerText;
                            string url = resultNode.Attributes["href"].Value;

                            searchResults.Add(new SearchResult { Title = title, Url = url });
                        }
                        return searchResults;
                    }
                }
                else
                {
                    Console.WriteLine("Failed to retrieve Bing search results.");
                }
            }

            return new List<SearchResult>();
        }

        async Task<string> DownloadHtmlContent(string url)
        {
            //Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    HttpResponseMessage response = await client.GetAsync(url);

                    if (response.IsSuccessStatusCode)
                    {
                        var byteArray = await response.Content.ReadAsByteArrayAsync();
                        return Encoding.GetEncoding(936).GetString(byteArray);
                    }
                }
                catch (HttpRequestException ex)
                {
                    Console.WriteLine($"Error: {ex.Message}");
                }

                return null;
            }
        }

        void ExtractChinesePhoneNumbersFromHtml(SearchResult result, string htmlContent)
        {
            if (htmlContent == null) return;
            string pattern = @"(?:\d{3}-\d{8}|\d{4}-\d{7})|(?:13\d{9})";
            Regex regex = new Regex(pattern);

            MatchCollection matches = regex.Matches(htmlContent);

            foreach (Match match in matches)
            {
                //Console.WriteLine("Phone Number: " + match.Value);
                ListViewItem item1 = new ListViewItem(result.Title);
                item1.SubItems.Add(result.Url);
                item1.SubItems.Add(match.Value);
                listView1.Items.Add(item1);
            }
        }
    }
    class SearchResult
    {
        public string Title { get; set; }
        public string Url { get; set; }
    }
}
